// utils/request.js
export const request = (url, method = 'GET', data = null, params = null) => {
  return new Promise((resolve, reject) => {
    // 处理GET参数
    let requestUrl = url
    if (method === 'GET' && params) {
      const queryString = Object.keys(params)
        .filter(key => params[key] != null) // 过滤undefined/null
        .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
        .join('&')
      requestUrl = `${url}?${queryString}`
    }

    uni.request({
      url: requestUrl,
      method,
      data: method === 'GET' ? null : data, // 关键点
      header: {
        'Content-Type': 'application/json',
        'Authorization': uni.getStorageSync('token') ? `Bearer ${uni.getStorageSync('token')}` : '',
      },
      success: (res) => {
        if (res.statusCode === 200) {
          resolve(res.data)
        } else {
          reject(new Error(res.data.message || `请求失败: ${res.statusCode}`))
        }
      },
      fail: (err) => {
        reject(new Error(`网络错误: ${err.errMsg}`))
      }
    })
  })
}